import 'package:myapp/http/core/adapter/net_adapter.dart';
import 'package:myapp/http/core/base_request.dart';

import 'adapter/dio_adapter.dart';
import 'net_response.dart';

class NetCore {
  final String _baseUrl;

  NetCore(this._baseUrl);

  /*
  异步
   */
  void enqueue(BaseRequest request) async {
    CoreResponse? response;
    var error;
    try {
      response = await _send(request);
    } catch (e) {
      error = e;
    }

    if (error != null) {
      print(error);
    }

    request.onAsyncFinish();

    var status = response?.statusCode;
    var result = response?.data;

    switch (status) {
      case 200:
        request.onAsyncSuccess(result);
      default:
        request.onAsyncFail((status ?? -8888).toString(),
            response?.stausMessage ?? result.toString());
    }
  }

  /*
  同步
   */
  Future<NetResponse<T>> execute<T>(BaseRequest request) async {
    CoreResponse? response;
    var error;
    try {
      response = await _send(request);
    } catch (e) {
      error = e;
    }

    if (error != null) {
      print(error);
    }

    var status = response?.statusCode;
    var result = response?.data;

    request.onSyncFinish();

    Future<NetResponse<T>> r;

    switch (status) {
      case 200:
        r = request.onSyncSuccess(response?.data);
      default:
        r = request.onSyncFail((status ?? -8888).toString(),
            response?.stausMessage ?? result.toString());
    }
    return r;
  }

  final DioAdapter _mAdapter = DioAdapter();

  Future<CoreResponse>? _send(BaseRequest request) {
    AbsNetAdapter adapter = _mAdapter;
    return adapter.send(_baseUrl, request);
  }
}
